package com.cxhome.cxinfox.customer;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cxhome.cxinfox.cxdepartment.DepartmentService;
import com.cxhome.cxinfox.order.Order;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.traffic.managent.annotation.ControllerBind;
import com.traffic.managent.base.CxBaseController;
import com.traffic.managent.model.account.Account;
import com.traffic.managent.model.customer.Customer;
import com.traffic.managent.model.product.Auditing;
import com.traffic.managent.model.system.User;
import com.traffic.managent.model.system.UserProsDiscountInfo;
import com.traffic.managent.util.SQLUtils;
import com.traffic.managent.util.StringUtils;
import com.traffic.managent.util.UtilsUtils;

/**
 * 客户管理
 * 
 * @author Guoxing
 *
 */
@ControllerBind(controllerKey = "/system/customerinfo")
public class CustomerController extends CxBaseController {

	private static final String path = "/pages/system/customerinfo/customerinfo_";

	public void index() {
		list();
	}
	/**
	 * 账单 
	 * 交易报表
	 */
	public void queryTransactionReports() {
		String customerId = getSessionUser().getStr("customerId");
		List<Record> list = CustomerService.service.queryTransactionReports(customerId);
		renderJson(list);
	}
	/**
	 * 账单 
	 * 交易记录 ，查询充值记录
	 */
	public void queryTransactionRecord() {
		String customerId = getSessionUser().getStr("customerId");
		int page = getParaToInt("page"); // page = (page-1) * number
		int pageNumber = getParaToInt("pageNumber");
		List<Account> list = CustomerService.service.queryTransactionRecord(customerId, page, pageNumber);
		renderJson(list);
	}
	
	/**
	 * 账单 
	 * 日对账 月对账
	 */
	public void queryStatistics() {
		String customerId = getSessionUser().getStr("customerId");
		String statisticsType = getPara("statisticsType");
		String statisticsDate = getPara("statisticsDate");
		List<Statistics> list = CustomerService.service.statisticsOrderDetailDay(customerId, statisticsDate,
				statisticsType);
		renderJson(list);
	}
	
	/**
	 * 订单
	 * 查询客户订购产品详情
	 */
	public void queryOrderList() {
		String customerId = getSessionUser().getStr("customerId");
		String departmentId = getSessionUser().getStr("departmentId");
		String start = getPara("startTime");
		String end = getPara("endTime");
		String ids = getPara("ids");
		String cstmOrderNo = getPara("cstmOrderNo");
		String phoneNo = getPara("phoneNo");
		String status = getPara("status");
		int page = getParaToInt("page"); // page = (page-1) * number
		int pageNumber = getParaToInt("pageNumber");
		List<Order> list = CustomerService.service.queryOrderList(customerId, departmentId, start, end, ids,
				cstmOrderNo, phoneNo, status, page, pageNumber);
		renderJson(list);
	}
	
	
	/**
	 * 产品 
	 * 查询客户在平台的折扣产品
	 */
	public void queryDiscountProduct() {
		String customerId = getSessionUser().getStr("customerId");
		List<UserProsDiscountInfo> list = CustomerService.service.queryDiscountProduct(customerId);
		renderJson(list);
	}
	
	/**
	 * 统计客户每天订单数（成功失败）与消费金额
	 */
	public void statisticsOrderDetailDay() {
		String statisticsDate = getPara("statisticsDate");
		String statisticsType = getPara("statisticsType");
		String customerId = getSessionUser().getStr("customerId");
		List<Statistics> list = CustomerService.service.statisticsOrderDetailDay(customerId, statisticsDate,statisticsType);
		renderJson(list);
	}
	
	
	/**
	 * 查询每月订单按小时分组，取订单金额最高的前10个小时
	 */
	public void queryHighAmount10Hour() {
		String customerId = getSessionUser().getStr("customerId");
		List<Record> list = CustomerService.service.queryHighAmount10Hour(customerId);
		renderJson(list);
	}
	
	
	/**
	 * 查询客户当前余额与信用额度
	 */
	public void queryAmountByCustomer() {
		Map<String, Object> map = new HashMap<String, Object>();
		String customerId = getSessionUser().getStr("customerId");
		Customer customer = CustomerService.service.queryAmountByCustomerId(customerId);
		// 现在余额+赠送余额
		map.put("amount", customer.getBigDecimal("amount").add(customer.getBigDecimal("giveAmount")));
		map.put("creditAmount", customer.getBigDecimal("creditAmount"));
		renderJson(map);
	}
	
	/**
	 * 每天成功的订单数
	 */

	public void queryDatyOrders() {
		Map<Integer, Object> map = new HashMap<Integer, Object>();

		String customerId = getSessionUser().getStr("customerId");
		Record list = CustomerService.service.queryMonthDayOrders(customerId);
		map.put(new Date().getMonth() + 1, list.getStr("nowMonthOrders"));
		renderJson(map);
	}
	/**
	 * 最近销量最高的10款产品
	 */
	
	public void queryHighProd() {
		List<Record> list = CustomerService.service.getHighProd();
		renderJson(list);

	}
	
	/**
	 * 客户年度/月度充值金额，消费金额
	 */
	
	public void queryAmount() {
		Map<String, Object> map = new HashMap<String, Object>();

		String customerId = getSessionUser().getStr("customerId");
		Record rechargerecord = CustomerService.service.rechargeAmountByTime(customerId);
		Record spendingrecord = CustomerService.service.spendingAmountByTime(customerId);
		map.put("yearRecharge", rechargerecord.getBigDecimal("yearRecharge"));
		map.put("monthRecharge", rechargerecord.getBigDecimal("monthRecharge"));
		map.put("yearSpending", spendingrecord.getBigDecimal("yearSpending"));
		map.put("monthSpending", spendingrecord.getBigDecimal("monthSpending"));
		renderJson(map);

	}
	public void list() {
		Customer model = getModelByAttr(Customer.class);

		SQLUtils sql = new SQLUtils(" from cx_customer_info pi where 1 = 1  ");

		if (model.getAttrValues().length != 0) {
			sql.whereEquals("delFlag", model.getStr("delFlag"));
			sql.whereLike("companyName", model.getStr("companyName"));
			sql.whereLike("customerId", model.getStr("customerId"));
		}

		// 排序
		String orderBy = getBaseForm().getOrderBy();
		if (StringUtils.isEmpty(orderBy)) {
			sql.append(" order by  createTime desc");
		} else {
			sql.append(" order by ").append(orderBy);
		}

		Page<Customer> page = Customer.dao.paginate(getPaginator(), "select pi.*  ", sql.toString().toString());
		// 下拉框
		setAttr("departSelect", DepartmentService.service.selectDepart(model.getStr("departid")));
		setAttr("selectCustomer", CustomerService.service.selectCustomer(model.getStr("customerId")));

		setAttr("page", page);
		setAttr("attr", model);
		render(path + "list.html");
	}

	public void add() {
		setAttr("departSelect", DepartmentService.service.selectDepart(""));

		render(path + "add.html");
	}

	public void view() {
		Customer model = Customer.dao.findById(getPara());

		setAttr("model", model);

		render(path + "view.html");
	}

	@Before(Tx.class)
	public void delete() {
		String naem = getSessionUser().getUserName();
		String customerId = getPara();
		// 1更新为删除状态
		Db.update("update cx_customer_info set delFlag = '1' where 1=1 and customerId =?", customerId);

		// 2并且该客户所关联的所有用户的状态改为停用
		List<User> list = User.dao.findByCustomerId(customerId);
		for (User user : list) {
			user.set("status", "0");// 0为停用
			user.update();
		}
		list();
	}

	public void edit() {
		Customer model = Customer.dao.findById(getPara());
		setAttr("model", model);
		render(path + "edit.html");
	}

	public void save() {
		String customerId = getPara();
		Customer model = getModel(Customer.class);

		String userid = getSessionUser().getUserName();
		String now = getNow();
		if (customerId != null) { // 更新
			model.put("updateName", userid);
			model.put("updateTime", now);
			model.update();
		} else { // 新增
			// 客户是否存在判断
			model.put("customerId", UtilsUtils.getRandomId(30));
			model.put("createName", userid);
			model.put("createTime", now);
			model.save();
		}
		renderMessage("保存成功");
	}

	/**
	 * 操作跳转
	 */
	public void operation() {
		String customerId = getPara();
		String type = getPara("type");// 操作类型：授信,ip鉴权,充值
		String customerName = getPara("customerName");
		try {
			customerName = new String(customerName.getBytes("iso8859-1"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String html = "";
		if ("recharge".equals(type)) {
			html = "recharge.html";
		} else if ("setCredit".equals(type)) {
			html = "setCredit.html";
		} else if ("ipList".equals(type)) {
			html = "ipList.html";
		}
		setAttr("customerId", customerId);
		setAttr("customerName", customerName);
		render(path + html);
	}

	/**
	 * 操作跳转页面确认 向审核表里头增加一条待审核的数据
	 */
	public void charge() {
		String customerId = getPara("customerId");
		String chargeAmount = getPara("chargeAmount") == "" ? "0.00" : getPara("chargeAmount");
		chargeAmount = chargeAmount.replaceAll(",", "");
		String giftAmount = getPara("giftAmount") == "" ? "0.00" : getPara("giftAmount");
		giftAmount = giftAmount.replaceAll(",", "");
		String customerName = getPara("customerName");
		String remark = getPara("remark");

		String createPerson = getSessionUser().getUserName();

		try {
			Auditing auditing = new Auditing();
			auditing.set("ids", UtilsUtils.getRandomId(30));
			auditing.set("auditingIds", customerId);
			auditing.set("customerName", customerName);
			auditing.set("type", "0");// 0加款，1授信，2其他
			auditing.set("status", "0");// 0待审核，1 通过，2驳回
			auditing.set("createPerson", createPerson);
			auditing.set("createTime", new Date());
			auditing.set("auditingIds", customerId);
			auditing.set("chargeAmount", chargeAmount);
			auditing.set("giftAmount", giftAmount);
			auditing.set("remark", remark);
			auditing.save();
		} catch (Exception e) {
			e.printStackTrace();

		}
		renderMessage("保存成功");
	}

	public void setCredit() {
		String customerId = getPara("customerId");
		String customerName = getPara("customerName");
		String remark = getPara("remark");

		String creditAmount = getPara("creditAmount") == "" ? "0.00" : getPara("creditAmount");
		creditAmount = creditAmount.replaceAll(",", "");
		String warnAmount = getPara("warnAmount") == "" ? "0.00" : getPara("warnAmount");
		warnAmount = warnAmount.replaceAll(",", "");
		String createPerson = getSessionUser().getUserName();
		try {
			Auditing auditing = new Auditing();
			auditing.set("auditingIds", customerId);
			auditing.set("ids", UtilsUtils.getRandomId(30));
			auditing.set("customerName", customerName);
			auditing.set("type", "1");// 0加款，1授信，2其他
			auditing.set("status", "0");// 0待审核，1 通过，2驳回
			auditing.set("createPerson", createPerson);
			auditing.set("createTime", new Date());
			auditing.set("auditingIds", customerId);
			auditing.set("creditAmount", creditAmount);
			auditing.set("warnAmount", warnAmount);
			auditing.set("remark", remark);
			auditing.save();

		} catch (Exception e) {
			e.printStackTrace();
			throw new ActiveRecordException(e.getMessage());

		}
		renderMessage("保存成功");
	}

	public void bindIps() {
		String customerId = getPara("customerId");
		String bindIps = getPara("bindIps");
		CustomerService.service.updateIps(customerId, bindIps);
		/*** bindIps字段更新后, 对应要更新缓存中appkey和bindIps的映射关系 ***/
		// // 先查询所有有绑定此客户ids的用户username(即appkey)
		// List<User> list = User.dao.findAllUsers(ids);
		// if (list != null && list.size() > 0) {
		// for (User user : list) {
		// // 将bindIps跟appkey映射放入缓存中
		// //
		// RedisKit.remove(ParamInitThread.cacheStart_bindips+user.getStr("username"));
		// RedisKit.put(ParamInitThread.cacheStart_bindips +
		// user.getStr("username"), ips);
		// synchronousBindIps(user.getStr("username"),ips);
		// }
		// }
		//
		renderMessage("保存成功");
	}
}
